package com.xjc.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serial;
import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @author xiaojincai
 * @since 2024-08-20
 */
@Data
@NoArgsConstructor
@Schema(description = "请求响应对象")
public class R<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 成功
     */
    public static final int SUCCESS = HttpServletResponse.SC_OK;

    /**
     * 失败
     */
    public static final int FAIL = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;

    @Schema(description = "消息状态码")
    private int code;

    @Schema(description = "消息内容")
    private String msg;

    @Schema(description = "数据对象")
    private T data;

    public static <T> R<T> ok() {
        return ok(null);
    }

    public static <T> R<T> ok(T data) {
        return ok("操作成功", data);
    }

    public static <T> R<T> ok(String msg, T data) {
        return restResult(data, SUCCESS, msg);
    }

    public static <T> R<T> fail() {
        return fail("操作失败");
    }

    public static <T> R<T> fail(String msg) {
        return fail(msg, null);
    }

    public static <T> R<T> fail(T data) {
        return fail("操作失败", data);
    }

    public static <T> R<T> fail(String msg, T data) {
        return restResult(data, FAIL, msg);
    }

    public static <T> R<T> fail(int code, String msg) {
        return restResult(null, code, msg);
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        final R<T> r = new R<>();
        r.setCode(code);
        r.setData(data);
        r.setMsg(msg);
        return r;
    }

    @JsonIgnore
    public boolean isOk() {
        return this.code == SUCCESS;
    }

}
